package sunyu.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import sunyu.config.Constant;
import sunyu.toolkit.core.LogKit;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author 孙宇
 */
public class MyFilter implements Filter {

    private static final Logger logger = LogKit.getLogger();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Subject subject = SecurityUtils.getSubject();
        String url = ((HttpServletRequest) servletRequest).getServletPath();
        logger.debug("访问的路径是 {}", url);
        if (subject.isPermitted(url) || subject.hasRole(Constant.superAdminRole)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            servletRequest.getRequestDispatcher(Constant.unauthorizedUrl).forward(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
